﻿using System.Diagnostics;

static class ListNodeExtensions
{
    public static IEnumerable<int> AsEnumerable(this ListNode node)
    {
        for (var current = node; current != null; current = current.next)
            yield return current.val;
    }
    public static ListNode? ToListNodes(this IEnumerable<int> ints)
    {
        ListNode listNode = new ListNode();
        ListNode? last = null;
        var current = listNode;
        foreach (var item in ints)
        {
            current.val = item;
            last = current;
            current = current.next = new ListNode();
        }
        if (last != null)
        {
            last.next = null;
            return listNode;
        }
        else
            return null;
    }
}

/// <summary>
/// https://leetcode-cn.com/problems/rotate-list/
/// </summary>
public class Solution
{
    public ListNode RotateRight(ListNode head, int k)
    {
        var ori = head.AsEnumerable();
        var count = ori.Count();
        if (count is 0)
            return head;

        k %= count;
        var starting = ori.TakeLast(k);
        var ending = ori.Take(count - k);
        var result = starting.Concat(ending).ToListNodes();
        Debug.Assert(result is not null);
        return result;
    }
}